<template>
  <view class="login-container">
    <view class="logo-section">
      <view class="logo"></view>
      <view class="title">欢迎登录</view>
    </view>
    
    <view class="form-section">
      <view class="input-group">
        <view class="input-icon">
          <text class="iconfont icon-user"></text>
        </view>
        <input type="text" v-model="username" placeholder="请输入用户名" placeholder-class="placeholder-style" />
      </view>
      
      <view class="input-group">
        <view class="input-icon">
          <text class="iconfont icon-password"></text>
        </view>
        <input type="password" v-model="password" placeholder="请输入密码" placeholder-class="placeholder-style" />
      </view>
      
      <view class="options">
          <checkbox-group @change="onCheckboxChange">
              <label>
                <checkbox value="rememberMe" :checked="rememberMe" />
                <text>记住我</text>
              </label>
            </checkbox-group>
          <text class="forget-password" @click="onForgetPassword">忘记密码？</text>
        </view>
      
      <button class="login-btn" @click="login" :disabled="loading">
        <text v-if="loading">登录中...</text>
        <text v-else>登录</text>
      </button>
      
      <view class="register-link">
        <text>还没有账号？</text>
        <text class="link" @click="goToRegister">立即注册</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      rememberMe: false,
      loading: false
    };
  },
  
  onLoad() {
    // 检查是否有保存的登录信息
    this.checkSavedLoginInfo();
  },

  methods: {
    
    // 检查是否有保存的登录信息
    checkSavedLoginInfo() {
      const savedUsername = uni.getStorageSync('savedUsername');
      const savedPassword = uni.getStorageSync('savedPassword');
      const rememberMe = uni.getStorageSync('rememberMe');
      
      if (rememberMe && savedUsername && savedPassword) {
        this.username = savedUsername;
        this.password = savedPassword;
        this.rememberMe = true;
      }
    },
    
    // 登录方法
    login: async function() {
      if (!this.username || !this.password) {
        uni.showToast({
          title: '请输入用户名和密码',
          icon: 'none'
        });
        return;
      }
      
      this.loading = true;
      
      try {
        // 构建登录数据
        const loginData = {
          account: this.username,
          password: this.password
        };
        
        console.log('登录请求:', loginData);
        
        // 使用uni.request进行网络请求
        const [err, res] = await new Promise((resolve) => {
          // 检查是否是模拟环境
          const isMock = true; // 在实际环境中可以根据配置设置
          
          if (isMock) {
            // 模拟环境下直接使用setTimeout模拟请求延迟
            setTimeout(() => {
              // 模拟登录成功响应
              const mockResponse = {
                data: {
                  code: 200,
                  message: '登录成功',
                  data: {
                    token: 'mock_token_' + Date.now(),
                    username: this.username,
                    userId: '123456'
                  }
                }
              };
              resolve([null, mockResponse]);
            }, 1500);
          } else {
            // 实际环境使用真实网络请求
            uni.request({
              url: 'http://localhost:8080/api/user/login',
              method: 'POST',
              data: loginData,
              success: (response) => resolve([null, response]),
              fail: (error) => resolve([error, null])
            });
          }
        });
        
        // 处理响应结果
        if (err || !res || res.data.code !== 200) {
          throw new Error(res?.data?.message || '网络请求失败');
        }
        
        const result = res.data;
        
        // 保存登录状态和用户信息
        uni.setStorageSync('isLoggedIn', true);
        uni.setStorageSync('username', this.username);
        uni.setStorageSync('token', result.data.token);
        
        // 处理记住我功能
        if (this.rememberMe) {
          uni.setStorageSync('rememberMe', true);
          uni.setStorageSync('savedUsername', this.username);
          uni.setStorageSync('savedPassword', this.password);
        } else {
          uni.removeStorageSync('rememberMe');
          uni.removeStorageSync('savedUsername');
          uni.removeStorageSync('savedPassword');
        }
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });
        
        // 跳转到首页
        uni.switchTab({
          url: '/pages/home/home'
        });
        
      } catch (error) {
        console.error('登录失败:', error);
        uni.showToast({
          title: error.message || '登录失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    onCheckboxChange: function(e) {
      const values = e.detail.value;
      this.rememberMe = values.includes('rememberMe');
    },
    
    // 忘记密码处理
    onForgetPassword: function() {
      uni.showModal({
        title: '忘记密码',
        content: '请联系客服重置密码',
        showCancel: false,
        confirmText: '确定'
      });
    },
    
    goToRegister: function() {
      uni.navigateTo({
        url: '/pages/auth/register'
      });
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 40rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  box-sizing: border-box;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
}

.logo {
  width: 180rpx;
  height: 180rpx;
  background-color: #FF6B6B;
  border-radius: 50%;
  margin-bottom: 30rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  width: 100%;
  max-width: 600rpx;
}

.input-group {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 0 30rpx;
  margin-bottom: 30rpx;
  height: 100rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.input-icon {
  margin-right: 20rpx;
  color: #999;
  font-size: 36rpx;
}

input {
  flex: 1;
  height: 100%;
  font-size: 32rpx;
  color: #333;
}

.placeholder-style {
  color: #ccc;
}

.options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  font-size: 28rpx;
  color: #666;
}

.forget-password {
    color: #FF6B6B;
    padding: 5px;
  }
  
  .forget-password:active {
    opacity: 0.7;
  }
  
  .login-btn:disabled {
    background-color: #ccc;
    color: #fff;
  }

.login-btn {
  width: 100%;
  height: 100rpx;
  background-color: #FF6B6B;
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
  border-radius: 50rpx;
  margin-bottom: 30rpx;
}

.login-btn:active {
  opacity: 0.8;
}

.register-link {
  display: flex;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
}

.link {
  color: #FF6B6B;
  margin-left: 10rpx;
}
</style>